
//
//  GGNetWorkHelper.m
//  TestAppDelegateService
//
//  Created by yuemei on 2017/9/22.
//  Copyright © 2017年 yuemei. All rights reserved.
//

#import "GGNetWork.h"
#import <YYKit/YYKit.h>
#import "GGNetWorkURLMatcher.h"
#define _GG_RSA_REQUEST_KEY @"sign"

@interface GGNetWorkHelper()
@property (nonatomic, copy) NSString *mac;
@property (nonatomic, copy) NSString *ifda;
@property (nonatomic, copy) NSString *market;
@property (nonatomic, copy) NSString *device;
@property (nonatomic, copy) NSString *uid;
@property (nonatomic, copy) NSString *sign;
@property (nonatomic, copy) NSString *appkey;
@property (nonatomic, copy) NSString *time;
@property (nonatomic, copy) NSString *ver;
@end

@implementation GGNetWorkHelper

// 解析json数据
+ (id)tryToParseData:(id)json {
    if (!json || json == (id)kCFNull) return nil;
    NSDictionary *dic = nil;
    NSData *jsonData = nil;
    if ([json isKindOfClass:[NSDictionary class]]) {
        dic = json;
    } else if ([json isKindOfClass:[NSString class]]) {
        jsonData = [(NSString *)json dataUsingEncoding : NSUTF8StringEncoding];
    } else if ([json isKindOfClass:[NSData class]]) {
        jsonData = json;
    }
    if (jsonData) {
        dic = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:NULL];
        if (![dic isKindOfClass:[NSDictionary class]]) dic = nil;
    }
    return dic;
}

//URL编码
+ (NSString *)urlEncode:(NSString *)url {
    if ([url respondsToSelector:@selector(stringByAddingPercentEncodingWithAllowedCharacters:)]) {
        
        static NSString * const kAFCharacterHTeneralDelimitersToEncode = @":#[]@";
        static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;=";
        
        NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
        [allowedCharacterSet removeCharactersInString:[kAFCharacterHTeneralDelimitersToEncode stringByAppendingString:kAFCharactersSubDelimitersToEncode]];
        static NSUInteger const batchSize = 50;
        
        NSUInteger index = 0;
        NSMutableString *escaped = @"".mutableCopy;
        
        while (index < url.length) {
            NSUInteger length = MIN(url.length - index, batchSize);
            NSRange range = NSMakeRange(index, length);
            range = [url rangeOfComposedCharacterSequencesForRange:range];
            NSString *substring = [url substringWithRange:range];
            NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
            [escaped appendString:encoded];
            
            index += range.length;
        }
        return escaped;
    } else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        CFStringEncoding cfEncoding = CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding);
        NSString *encoded = (__bridge_transfer NSString *)
        CFURLCreateStringByAddingPercentEscapes(
                                                kCFAllocatorDefault,
                                                (__bridge CFStringRef)url,
                                                NULL,
                                                CFSTR("!#$&'()*+,/:;=?@[]"),
                                                cfEncoding);
        return encoded;
#pragma clang diagnostic pop
    }
}


//时间戳
+ (NSString *)unixTime {
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a = [dat timeIntervalSince1970];
    return [NSString stringWithFormat:@"%.f", a];
}

+ (BOOL)dataCacheTimeoutWithInterval:(NSInteger)intervalTime URL:(NSString *)URL parameters:(id)parameters{
    
    NSDate *cacheTime = [GGNetWorkCache netWorkCacheTimeForURL:URL parameters:parameters];
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
    NSTimeInterval time = [localeDate timeIntervalSinceDate:cacheTime];
    
    int minutes = ((int)time/60);
    //    int seconds = ((int)time)%(3600*24)%3600%60;
    
    BOOL timeout;
    if (cacheTime) {
        if (minutes > intervalTime || minutes < 0) {
            timeout = YES;
        }else{
            timeout = NO;
        }
        
    }else{
        timeout = YES;
    }
    
    return timeout;
}

+ (NSString *)cacheKeyWithURL:(NSString *)URL parameters:(NSDictionary *)parameters {
    if(!parameters || parameters.count == 0){return URL;};
    NSError *error;
    // 将参数字典转换成字符串
    NSData *stringData;
    @try{
       stringData  = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error];
        if (error){return URL;};
    }
    @catch (NSException *exception){
        return URL;
    }
    @finally {
        return URL;
    }
   
    
    NSString *paraString = [[NSString alloc] initWithData:stringData encoding:NSUTF8StringEncoding];
    NSString *cacheKey = [NSString stringWithFormat:@"%@%@",URL,paraString];
    
    return [NSString stringWithFormat:@"%ld",(unsigned long)cacheKey.hash];
}




@end
